﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Data;
using System.Web.UI.WebControls;

using Frame.Lib.Core.Base;
using Frame.Lib.Web;
using Frame.Lib.Core.Dept;
using Frame.Lib.Common;
using Frame.Lib.Core.Role;
using Frame.Lib.Enums;
using Frame.Lib.Core.Tree;
using Frame.Lib.Core.Module;
using Frame.Lib.Utilities;

namespace Frame.Lib.Core.User
{
    public class UserBO : CommonOperate<UserInfo>, IModuleAccess
    {
        private UserDAL _user = new UserDAL();
        public UserBO()
            : base()
        {

        }
        protected override BaseDAL DAL
        {
            get
            {
                return _user;
            }
        }

        public List<UserInfo> GetList(PagerSetting pager,string condition,ref int stopCount)
        {
            pager.Where = _user.GetPagerCondition(condition);


            List<UserInfo> list = base.GetList(pager, "%" + condition + "%");

            stopCount = _user.GetStopedUserCount(condition);

            _user.AddDeptName(list);

            return list;
        }

        public IEnumerable<UserInfo> GetList(int deptID, PagerSetting pager,string condition,ref int stopCount)
        {
            DeptBO dept = new DeptBO();
            List<int> subIDs = dept.GetSubIDs(deptID);

            string sortExpression = "Orders";
            string sortDirection = "asc";



            if (!string.IsNullOrEmpty(pager.OrderBy))
            {
                sortExpression = pager.OrderBy.Split(' ')[0];
                sortDirection = pager.OrderBy.Split(' ')[1];
            }

            IEnumerable<UserInfo> list = _user.GetListByDept(subIDs);

            if (!string.IsNullOrEmpty(condition))
            {
                list = list.Where(tmp => tmp.Name.Contains(condition) || tmp.LoginName.Contains(condition));
            }

            list = list.ToList();

            pager.RecordCount = list.Count();

            if (sortDirection == "desc")
            {
                list = list.OrderByDescending(tmp => tmp.GetType().GetProperty(sortExpression).GetValue(tmp, null));
            }
            else
            {
                list = list.OrderBy(tmp => tmp.GetType().GetProperty(sortExpression).GetValue(tmp, null));
            }

            stopCount = list.Where(tmp => tmp.Status == (int)UserStatus.停用).Count();

            list = list.Skip((pager.PageIndex-1) * pager.RecordCount).Take(pager.PageSize);

            _user.AddDeptName(list);

            return list;
        }

        public override UserInfo GetInfo(object id)
        {
            UserInfo info = base.GetInfo(id);

            Decript(info);
            if (id != null)
            {
                List<int> deptIDs = UserDAL.GetDeptIDs(Convert.ToInt32(id)).ToList();
                info.DeptIDs = deptIDs;
                info.DeptName = StrUtil.MergeToStr((new DeptBO()).GetName(deptIDs), ",");

                info.GetRoleIDs = userID => _user.GetRoleIDs(userID);
            }
            return info;
        }

        public override void Save(UserInfo info)
        {
            bool isAdd = (info.ID == 0) ? true : false;
            this.Save(info, isAdd);
        }

        public override void Save(UserInfo info, bool isInsert)
        {
            Encript(info);
            if (isInsert)
            {
                info.ID = GetSequenceID();
            }
            base.Save(info, isInsert);
            _user.SaveDept(info);

            if (isInsert)
            {
                string roleID = AppSetting.UserDefaultRoleID;
                if (roleID != null && roleID != "")
                {
                    RoleBO role = new RoleBO();
                    role.AddUserID(int.Parse(roleID), info.ID);
                }
            }
        }

        public void ModifyPwd(UserInfo info)
        {
            Encript(info);
            base.Save(info, false);
        }


        //public List<UserInfo> GetList(IEnumerable<int> userIDs)
        //{
        //    List<UserInfo> list = _user.GetList(userIDs);
        //    return list;
        //}

        public List<UserInfo> GetListByRoleIDs(string strRoleIDs)
        {
            List<UserInfo> list = _user.GetListByRoleIDs(strRoleIDs);
            return list;
        }

        public UserInfo GetInfoByLoginName(string strLoginName)
        {
            object id = _user.GetID(strLoginName);
            UserInfo info = null;
            if (id != null)
            {
                info = GetInfo(id);
            }
            return info;
        }



        public LoginResult CheckLogin(string strLoginName, string strPassword)
        {
            LoginResult result = LoginResult.Success;

            UserInfo info = this.GetInfoByLoginName(strLoginName);
            if (info == null)
            {
                if (strLoginName == Constants.ADMIN_NAME)//超级管理员的初始化
                {
                    info = new UserInfo();
                    info.ID = Constants.ADMIN_ID;
                    info.LoginName = Constants.ADMIN_NAME;
                    info.Name = "系统保留用户";
                    info.Password = Constants.ADMIN_PWD;
                    info.Orders = 0;
                    info.Status = (int)UserStatus.启用;
                    Encript(info);//加密密码

                    _user.SaveAdmin(info);
                    result = CheckLogin(strLoginName, strPassword);
                }
                else
                {
                    result = LoginResult.UserErr;
                }
            }
            else
            {
                if (info.Status == (int)UserStatus.启用)
                {
                    if (info.Password == strPassword)
                    {
                        result = LoginResult.Success;
                    }
                    else
                    {
                        result = LoginResult.PwdErr;
                    }
                }
                else
                {
                    result = LoginResult.Forbidden;
                }

            }
            return result;
        }

        private void Encript(UserInfo info)
        {
            info.Password = StrUtil.EncryptDES(info.Password, info.LoginName);
        }

        private void Decript(UserInfo info)
        {
            try
            {
                info.Password = info.DecryptPassword = StrUtil.DecryptDES(info.Password, info.LoginName);
            }
            catch
            {
                info.Password = "";
            }
        }

        public IEnumerable<int> GetModuleIDs(int userID, RoleBO role)
        {
            IEnumerable<int> moduleIDs = _user.GetModuleIDs(userID);//直接分配给用户的模块
            IEnumerable<int> roleIDs = _user.GetRoleIDs(userID);//用户拥有哪些角色

            IEnumerable<int> roleModuleIDs = role.GetModuleIDs(roleIDs);//角色所拥有的模块

            return moduleIDs.Concat(roleModuleIDs);
        }



        public void BindDeptUserTree(System.Web.UI.WebControls.TreeView tvDeptUser, bool allowCheckDept, List<int> lstSelectIDs)
        {
            List<TreeInfo> trees = _user.GetDeptUserList();
            if (allowCheckDept)
            {
                foreach (TreeInfo info in trees)
                {
                    info.ShowCheckBox = true;
                }
               
            }
            TreeBO<TreeInfo> tree = new TreeBO<TreeInfo>(STableName.Dept);
            tree.BindTreeView(tvDeptUser, trees, true, lstSelectIDs);

            //把没有部门的用户找出来
            //dt = user.GetNoneDeptList();
            //TreeNode node = new TreeNode(Jzy.Common.Constants.NONE_DEPT, "0");
            //node.ShowCheckBox = false;
            //foreach (DataRow dr in dt.Rows)
            //{
            //    node.ChildNodes.Add(new TreeNode(dr["Name"].ToString(), "-" + dr["ID"]));
            //}
            //tvDeptUser.Nodes[0].ChildNodes.Add(node);
        }

        public void Startup(IEnumerable<int> lstUserIDs)
        {
            _user.Startup(lstUserIDs);
        }

        public void Stop(IEnumerable<int> lstUserIDs)
        {
            _user.Stop(lstUserIDs);
        }

        public List<int> GetRoleIDs(int userID)
        {
            List<int> roleIDs = _user.GetRoleIDs(userID).ToList();
            return roleIDs;
        }

        #region IModuleAccess 成员

        public List<int> GetModuleIDs(int userID)
        {
            List<int> lstModuleIDs = _user.GetModuleIDs(userID).ToList();
            return lstModuleIDs;
        }

        public void SaveModuleIDs(int userID, List<int> lstModuelIDs)
        {
            _user.SaveModuleIDs(userID, lstModuelIDs);
        }

        #endregion

        public void MoveDept(List<int> userIDs, int deptID)
        {
            _user.MoveDept(userIDs, deptID);
        }


        public List<TreeInfo> GetDeptUserList()
        {
            return _user.GetDeptUserList();
        }
    }
}
